package br.com.extrajudicial.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Hibernate;
import br.com.caelum.vraptor.view.Results;
import br.com.extrajudicial.dao.AddressDao;
import br.com.extrajudicial.dao.UserDao;
import br.com.extrajudicial.interceptors.RequireUser;
import br.com.extrajudicial.models.Address;
import br.com.extrajudicial.models.User;

@Resource
public class AddressesController {
	
	@Autowired private Validator validator;
	@Autowired private AddressDao addressDao;
	@Autowired private UserDao userDao;
	@Autowired private Result result;
	
	@Get @Path("/addresses") 
	public List<Address> addresses() {
		return this.addressDao.listAll();
	}
	
	@Get @Path("/addresses/add")
	@RequireUser
	public void add() { 
		findUsers();
	}

	@Post @Path("/addresses")
	@RequireUser
	public void save(Address address) {
		findUsers();
		this.validator.addAll(Hibernate.validate(address));
		this.validator.onErrorUse(Results.page()).of(AddressesController.class).add();
		this.addressDao.save(address);
		redirectToAddresses();
	}
	
	@Get @Path("/addresses/{id}/edit")
	@RequireUser
	public Address edit(Long id) {
		findUsers();
		return this.addressDao.load(id);
	}
	
	@Put @Path("/addresses")
	@RequireUser
	public void update(Address address) {
		findUsers();
		this.validator.addAll(Hibernate.validate(address));
		this.validator.onErrorUse(Results.page()).of(AddressesController.class).edit(address.getId());
		this.addressDao.update(address);
		redirectToAddresses();
	}
	
	@Delete @Path("/addresses/{id}")
	@RequireUser
	public void delete(Long id) {
		Address address = this.addressDao.load(id);
		this.addressDao.delete(address);
		redirectToAddresses();
	}
	
	@Get @Path("/addresses/search")
	public List<Address> search(String query) {
		this.result.include("query", query);
		return this.addressDao.search(query);
	}

	private void redirectToAddresses() {
		this.result.redirectTo(AddressesController.class).addresses();
	}

	private void findUsers() {
		List<User> users = this.userDao.listAll();
		this.result.include("users", users);
	}
		
}
